import { Body, Controller, Delete, Get, Post, Put, Query, UseGuards, UsePipes } from "@nestjs/common";
import { WebURLConstants } from '../../../WebURLConstant'
import { OrgService } from "./org.service";
import { AddOrgDto } from "./dto/addOrgDto";
import { restBody, restPageBody } from "src/store/vo/BodyDto";
import { AuthGuard } from "src/auth/guard/auth.guard";
import { log } from "console";
import { orgPageDto } from "./dto/pageOrgDto";
import { PageSatrtPipe } from "src/utils/page.pipe";
import { SingleIdDto } from "src/store/dto/SingleIdDto";
import { EditOrg } from "./dto/editOrgDto";
import { UpdateOrg } from "./dto/deleteOrgDto";
import { DataPermission } from "src/auth/guard/data.permission";
import { Roles } from "src/auth/guard/roles.decorator";
import { DataHandle } from "src/auth/guard/data.handle";
import { OrgTreeDto } from "./dto/orgTreeDto";

@UseGuards(AuthGuard)
@Controller(WebURLConstants.ORG)
export class OrgCantroller {

  constructor(
    private orgService: OrgService
  ) { }

  /**
   * 查询指定组织及所有下级组织
   * @param orgId 组织Id
   * @returns 扁平数组
   */
  @Get(WebURLConstants.ORGTREE)
  async getOrgTree(@Query() dto: OrgTreeDto) {

    log('get-body', dto)

    return restBody(await this.orgService.getOrgTree(dto.id))
  }

  /**
   * 新增组织架构
   * @param dto 参数
   * @returns true or false
   */
  @Post(WebURLConstants.ADD)
  @Roles('org_add') // 权限标识
  @UseGuards(DataHandle) // 操作验证权限
  async addOrg(@Body() dto: AddOrgDto) {

    log('post-body', dto)

    const result = await this.orgService.addOrg(dto)
    return restBody(result)
  }

  /**
   * 查询组织架构分页
   * @param params 参数
   * @returns 列表数据和总数
   */
  @Post(WebURLConstants.PAGE)
  @UseGuards(DataPermission) // 数据权限验证
  @UsePipes(PageSatrtPipe) // 处理默认参数
  async orgPage(@Body() params: orgPageDto) {

    log('post-body', params)

    const result = await this.orgService.orgPage(params)
    return restPageBody(result)
  }

  /**
   * 查询组织架构详情
   * @param params 参数
   * @returns 详情
   */
  @Get(WebURLConstants.DETAIL)
  @Roles('org_detail')
  @UseGuards(DataHandle)
  async getDetail(@Query() params: SingleIdDto) {

    log('get-query', params)

    const detail = await this.orgService.getDetail(params)

    return restBody(detail)
  }

  /**
   * 修改组织架构
   * @param dto 参数
   * @returns true or false
   */
  @Put(WebURLConstants.EDIT)
  @Roles('org_edit')
  @UseGuards(DataHandle)
  async editOrg(@Body() dto: EditOrg) {

    log('put-query', dto)

    const result = await this.orgService.editOrg(dto)

    return restBody(result)
  }

  /**
   * 删除组织架构
   * @param params 参数
   * @returns true or false
   */
  @Delete(WebURLConstants.DELETE)
  @Roles('org_delete')
  @UseGuards(DataHandle)
  async deleteOrg(@Query() params: UpdateOrg) {

    log('delete-query', params)

    const result = await this.orgService.deleteOrg(params)

    return restBody(result)
  }
}